package cn.yufan.controller;

import cn.yufan.entity.Admin;
import cn.yufan.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 管理员和用户登录控制层
 */
@Controller
@EnableAutoConfiguration
public class LoginController {
    @Autowired
    private AdminService adminService;

    /**
     * 验证管理员信息
     */
    @RequestMapping(value = "/back/validateAdminInfo")
    @ResponseBody
    public boolean checkLoginInfo(Admin admin,HttpServletRequest request) {
        Admin newAdmin=null;
        try {
            //根据管理员姓名和密码或手机号码查询
            newAdmin=adminService.login(admin);
            if(newAdmin!=null){
                request.getSession().setAttribute("admin",admin);
                return true;
            }
            return false;
        }catch (Exception e){
            return false;
        }
    }
    @RequestMapping("/back/logout")
    public void Logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //清除session中的数据
        request.getSession().invalidate();
        //清除cookie中的数据
        Cookie[] cookies=request.getCookies();
        for(Cookie cookie: cookies){
            cookie.setMaxAge(0);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
}
